/*
 * $LastChangedDate: 2007-06-22 00:05:41 +0200 (Fri, 22 Jun 2007) $
 * $LastChangedRevision: 211 $
 * $LastChangedBy: vicente $
 */

import java.util.*;
import java.io.*;
import java.net.*;


public class Server extends Thread
{
        public ServerSocket serverSocket = null;
	public Socket clientSocket = null;
    
	private static final int PORT = 4242;
	private HashMap<String,FileLock> locks = new HashMap<String,FileLock>();

	public Server(String str)
	{
		super(str);
		Log.println("server creado", Log.INIT);
	}

	/**
	 * Obtiene el FileLock para un fichero.
	 *
	 * @return Devuelve el FileLock asociado al fichero con path 'path'
	 */
	private FileLock getFileLock(String path)
	{
		FileLock lock;

		/* Obtenemos el cerrojo para el fichero o, si no existe, lo
		 * creamos */
		if (locks.containsKey(path)) {
			lock = (FileLock) locks.get(path);
		} else {
			lock = new FileLock();
			locks.put(path, lock);
		}
		return lock;
	}

	
	public void run()
	{
		
		boolean listening = true;

		try {
			Log.println("escuchando en el puerto " + PORT, Log.CONNECTION);
			serverSocket = new ServerSocket(PORT);
		} catch (IOException e) {
			Log.println("Could not listen on port: " + PORT);
			System.exit(1);
		}


		try {
			while (listening) {
				clientSocket = serverSocket.accept();
				Log.println("Aceptado conexión " + clientSocket, Log.CONNECTION);
				PrintWriter out = new
					PrintWriter(clientSocket.getOutputStream(), true);
				BufferedReader in = new BufferedReader(new
					InputStreamReader(clientSocket.getInputStream()));

				String path = in.readLine();
				File f = new File(path);

				new FileMngr(f, getFileLock(path), clientSocket).start();
				out.println("Creado FileMngr para " + path);
                                
			}

			serverSocket.close();
		} 
                catch (SocketException s) {
                        System.out.println("Apagando servidor ...");
                }
                catch (IOException e) {
			Log.println("Exception: " + e);
			System.exit(1);
		}
	}

	public String toString()
	{
		return "Server";
	}
}
